package hk.ust.comp3111.ustnutrition.formula;

import java.util.Date;
import java.util.GregorianCalendar;

import android.util.Log;

import hk.ust.comp3111.ustnutrition.MiscUtils;
import hk.ust.comp3111.ustnutrition.data.db.User;

public class ScoreCalculator {
	public static final String TAG = "hk.ust.comp3111.ustnutrition.formula.ScoreCalculator";
	
	public ScoreCalculator(User user) {
		mUser = user;
		cal = new NutritionCalculator(user);
	}

	User mUser;
	NutritionCalculator cal;
	
	public double getDailyScore() {
		return getDailyScore(new Date());
	}

	public Double getDailyScore(Date date) {
		double CarbohydratesScore, ProteinScore, FatScore, SodiumScore, TotalScore; // score
		double CarbohydratesNeed, ProteinNeed, FatNeed, SodiumNeed; // nutrition
																	// need
		double CarbohydratesConsumption, ProteinConsumption, FatConsumption, SodiumConsumption;

		cal.calc();
		CarbohydratesNeed = cal.getCarbohydratesNeed();
		ProteinNeed = cal.getProteinNeed();
		FatNeed = cal.getFatNeed();
		SodiumNeed = cal.getSodiumNeed();

		double[] val = mUser.getNutritions(date);
		CarbohydratesConsumption = val[1];
		ProteinConsumption = val[2];
		FatConsumption = val[3];
		SodiumConsumption = val[4];
		
		if(val[0] == 0 && val[1] == 0 && val[2] == 0 && val[3] == 0 && val[4] == 0)
			return null;

		if (CarbohydratesConsumption <= CarbohydratesNeed)
			CarbohydratesScore = 65 * CarbohydratesConsumption
					/ CarbohydratesNeed;
		else
			CarbohydratesScore = Math.max(0,
					65 - (CarbohydratesConsumption - CarbohydratesNeed) / 5);

		if (ProteinConsumption <= ProteinNeed)
			ProteinScore = 15 * ProteinConsumption / ProteinNeed;
		else
			ProteinScore = Math.max(0,
					15 - (ProteinConsumption - ProteinNeed) / 1.25);

		if (FatConsumption <= FatNeed)
			FatScore = 10 * FatConsumption / FatNeed;
		else
			FatScore = Math.max(0, 10 - (FatConsumption - FatNeed));

		if (SodiumConsumption <= SodiumNeed)
			SodiumScore = 10 * SodiumConsumption / SodiumNeed;
		else
			SodiumScore = Math
					.max(0, 10 - 2 * (SodiumConsumption - SodiumNeed));

		TotalScore = (double) Math.round((CarbohydratesScore + ProteinScore
				+ FatScore + SodiumScore) * 10) / 10.0; // round to 1 decimal
														// place

		return TotalScore;
	}
	
	public double getWeeklyScore() {
		Date today = new Date();
		GregorianCalendar c = new GregorianCalendar();
		c.setTime(today);
		double score = 0;
		int total = 0;
		for(int i = 1; i <= 7; i++) {
			c.set(GregorianCalendar.DAY_OF_WEEK, i);
			if(MiscUtils.getDate(c.getTime()) > MiscUtils.getDate(today))
				break;
			Log.i(TAG, "Calculating " + c.getTime());
			Double dscore = getDailyScore(c.getTime());
			if(dscore != null) {
				score += dscore;
				total++;
			}
		}
		if(total == 0)
			return 0;
		return score / total;
	}
}

